package ink.lovejinhu.swardToOffer;

import ink.lovejinhu.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author jinhu
 * created 2021-08-12 10:20
 */
public class Offer_032_III {
    /**
     * linkedList是双端队列
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            List<List<Integer>> outer = new ArrayList<>();
            return outer;
        }
        LinkedList<TreeNode> treeNodes = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        treeNodes.add(root);
        int flag = 1;
        while (!treeNodes.isEmpty()) {
            LinkedList<Integer> integers = new LinkedList<>();
            for (int i = treeNodes.size(); i > 0; i--) {
                TreeNode pop = treeNodes.poll();
                if (flag % 2 == 1) {
                    integers.addFirst(pop.val);
                } else {
                    integers.addLast(pop.val);
                }
                if (pop.left != null) {
                    treeNodes.add(pop.left);
                }
                if (pop.right != null) {
                    treeNodes.add(pop.right);
                }
            }
            flag++;
            res.add(integers);

        }
        return res;
    }

    public static void main(String[] args) {
        Offer_032_III offer_032_iii = new Offer_032_III();
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode3.right = treeNode5;
        List<List<Integer>> lists = offer_032_iii.levelOrder(treeNode1);
        System.out.println(lists);
    }
}
